package com.pci.netty.util;

import cn.hutool.crypto.SecureUtil;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;

public class AESUtils {
    private final static byte[] SEC_KEY = SecureUtil.decode("cDAY6TQx+PnSF2/eHPKVKaiKkTOwCpbGuDmlbmxFD80=");

    /**
     * 解码
     *
     * @param body
     * @return
     */
    public static String decrypt(byte[] body) {
        try {
            byte[] decrypt = SecureUtil.aes(SEC_KEY).decrypt(body);
            return new String(decrypt, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 加密
     *
     * @param body
     * @return
     */
    public static String encryptStr(byte[] body) {
        return new String(encrypt(body), StandardCharsets.UTF_8);
    }

    public static byte[] encrypt(byte[] body) {
        try {
            return SecureUtil.aes(SEC_KEY).encrypt(body);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成aes秘钥
     *
     * @param len 生成密钥的长度，可以为128, 192或256
     * @return
     */
    public static String genAesSecret(int len) {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(len);
            SecretKey secretKey = keyGenerator.generateKey();
            return Base64.encodeBase64String(secretKey.getEncoded());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }


}
